<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px" @submit.prevent>
      <el-form-item label="供应商" prop="supplierName">
        <el-input
          v-model.trim="queryParams.supplierName"
          placeholder="请输入供应商"
          clearable
          @keyup.enter="handleQuery"
          style="width: 175px"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:supplier:add']"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:supplier:edit']"
        >修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:supplier:remove']"
        >批量删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:supplier:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Download"
          @click="downloadSupplier"
        >下载导入模板</el-button>
      </el-col>
      <el-col :span="1.5">
        <MyUpload
          buttonName="导入供应商信息" 
          url="/api/supplier/import"
          @success="handleUploadSuccess"
          @warning="handleUploadWarning"
          />
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <TableScrollContainer :topHeight="220">
      <template #default="{ tableHeight }">
    <el-table v-loading="loading" :data="supplierList" @selection-change="handleSelectionChange" :height="tableHeight" border>
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="供应商id" align="center" prop="supplierId" /> -->
      <el-table-column label="供应商" align="center" prop="supplierName" />
      <el-table-column label="联系人" align="center" prop="contactPerson" />
      <el-table-column label="联系电话" align="center" prop="contactPhone" />
      <el-table-column label="联系邮箱" align="center" prop="contactEmail" />
      <el-table-column label="地址" align="center" prop="address" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="状态" align="center" prop="status">
        <!-- <template #default="scope">
          <dict-tag :options="supplier_status" :value="scope.row.status"/>
        </template> -->
        <template #default="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="0"
            :inactive-value="1"
            :loading="switchLoading[scope.row.supplierId]"
            style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
            @change="changeStatus(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="190" fixed="right">
        <template #default="scope">
          <el-button type="success" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:supplier:edit']">修改</el-button>
          <el-button type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:supplier:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page-sizes="[10, 30, 50, 100]"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
      </template>
    </TableScrollContainer>

    <!-- 添加或修改供应商对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" :close-on-click-modal="false">
      <el-form ref="supplierRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="供应商" prop="supplierName">
          <el-input v-model="form.supplierName" placeholder="请输入供应商" />
        </el-form-item>
        <el-form-item label="联系人" prop="contactPerson">
          <el-input v-model="form.contactPerson" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="联系邮箱" prop="contactEmail">
          <el-input v-model="form.contactEmail" placeholder="请输入联系邮箱" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入地址" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入内容" />
        </el-form-item>
        <!-- <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in supplier_status"
              :key="dict.value"
              :label="parseInt(dict.value)"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Supplier">
import { listSupplier, getSupplier, delSupplier, addSupplier, updateSupplier, updateStatusAPI } from "@/api/work/supplier"
import TableScrollContainer from '@/components/Pagetable/TableScrollContainer.vue'

const { proxy } = getCurrentInstance()
const { supplier_status } = proxy.useDict(['supplier_status'])

const supplierList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const switchLoading = ref({})

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    supplierName: null,
  },
  rules: {
    supplierName: [
      { required: true, message: '请输入供应商', trigger: 'blur' }
    ],
    contactPerson: [
      { required: true, message: '请输入联系人', trigger: 'blur' }
    ],
    contactPhone: [
      { required: true, message: '请输入联系电话', trigger: 'blur' }
    ],
    contactEmail: [
      { required: true, message: '请输入联系邮箱', trigger: 'blur' }
    ],
    address: [
      { required: true, message: '请输入地址', trigger: 'blur' }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询供应商列表 */
function getList() {
  loading.value = true
  listSupplier(queryParams.value).then(res => {
    if (res.errCode === '1') {
      supplierList.value = res.data.page.records
      total.value = res.data.page.total
      loading.value = false
    }
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    supplierId: null,
    supplierName: null,
    contactPerson: null,
    contactPhone: null,
    contactEmail: null,
    address: null,
    remark: null,
    status: null,
    version: null,
    updateBy: null,
    updateTime: null,
    createdBy: null,
    createTime: null
  }
  proxy.resetForm("supplierRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.supplierId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加供应商"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _supplierId = row.supplierId || ids.value
  getSupplier(_supplierId).then(res => {
    form.value = res.data.supplier
    open.value = true
    title.value = "修改供应商"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["supplierRef"].validate(valid => {
    if (valid) {
      if (form.value.supplierId != null) {
        updateSupplier(form.value).then(res => {
          if (res.errCode === '1') {
            proxy.$modal.msgSuccess("修改成功")
            open.value = false
            getList()
          } else {
            proxy.$modal.msgError(res.msg)
          }
        })
      } else {
        addSupplier(form.value).then(res => {
          if (res.errCode === '1') {
            proxy.$modal.msgSuccess("新增成功")
            open.value = false
            getList()
          } else {
            proxy.$modal.msgError(res.msg)
          }
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _supplierIds = row.supplierId || ids.value
  proxy.$modal.confirm('是否确认删除供应商编号为"' + _supplierIds + '"的数据项？').then(function() {
    return delSupplier(_supplierIds)
  }).then(res => {
    if (res.errCode === '1') {
      getList()
      proxy.$modal.msgSuccess("删除成功")
    }
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('/api/supplier/export', {
    ...queryParams.value
  }, `供应商数据_${new Date().getTime()}.xlsx`)
}

// 下载模板
const downloadSupplier = async() => {
  proxy.download('/api/supplier/downloadTemplate', {}, `供应商模板_${new Date().getTime()}.xlsx`)
}
// 上传成功后的回调
const handleUploadSuccess = (res) => {
  getList()
}

const handleUploadWarning = (res) => {
  getList()
}

getList()

const changeStatus = async(row) => {
  // 设置当前行的switch为loading状态
  switchLoading.value[row.supplierId] = true
  
  try {
    const submitForm = {
      supplierId: row.supplierId,
      status: row.status
    }
    const res = await updateStatusAPI(submitForm)
    if (res.errCode === '1') {
      getList()
      proxy.$modal.msgSuccess('更新成功')
    } else {
      getList()
      proxy.$modal.msgError(res.msg)
    }
  } catch(err) {
    getList()
  } finally {
    // 无论成功失败，都关闭loading
    switchLoading.value[row.supplierId] = false
  }
}
</script>
